//
//  ForgotPasswordViewController.m
//  PalmChangtu
//
//  Created by osoons on 15/6/23.
//  Copyright (c) 2015年 PalmChangtu. All rights reserved.
//

#import "ForgotPasswordViewController.h"

#import "AFNetworking.h"
#import "LoadingView.h"
#import "NetWarningView.h"
#import "BaseUrlConfig.h"
#import "LoadingView.h"
#import "NetWarningView.h"
#import "AFNetworking.h"
#import "BaseUrlConfig.h"
#import "TestCollectionViewController.h"
#import "UIImageView+AFNetworking.h"
#import "UIImageView+WebCache.h"

#import "all_commodity_TypeModel.h"
#import "localJSONModel.h"
#import "MTLJSONAdapter.h"
#import "MainTabbarController.h"
#import "ContactUSViewController.h"
#import "ShareUserModel.h"
#import "BaseUrlConfig.h"
#import "LoginViewController.h"
#import "Common.h"
#import "GTMDefines.h"
#import "GTMBase64.h"
#import "UIImageView+AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "NotLoggedInViewController.h"
@interface ForgotPasswordViewController ()
{
    NSInteger countdownTiem60;

}
@end

@implementation ForgotPasswordViewController
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    countdownTiem60 = 60;

    [_v_Top.lalTitel setText:@"忘记密码"];
    [_v_Top.btnGoback setHidden:NO];
    _v_Top.parentController = self.navigationController;
    
    [_v_Top.btnGoback removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_v_Top.btnGoback addTarget:self action:@selector(btnBack:) forControlEvents:UIControlEventTouchUpInside];


    [_btnVerification removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    [_btnVerification addTarget:self action:@selector(btnVerification:) forControlEvents:UIControlEventTouchUpInside];

    [_textPhoneNum becomeFirstResponder];


    // Do any additional setup after loading the view from its nib.
}


-(void)btnVerification:(UIButton *)Verification
{



    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];


    [self.btnVerification setTitle:[NSString stringWithFormat:@"%@秒",[NSNumber numberWithInteger:countdownTiem60]] forState:UIControlStateNormal];

    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(ActionRepeats:) userInfo:nil repeats:YES];

    BOOL isNum = [self VerifyMobileNumber:_textPhoneNum.text];



    if (!isNum) {

        UIAlertView * aler = [[UIAlertView alloc ] initWithTitle:@"提示" message:@"手机号码有误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [aler show];
        return;
    }



    [self VerifyCodeRequest];

}

//检测是否是手机号码
- (BOOL)VerifyMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     * 虚拟：170
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9]|70)\\d{8}$";

    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    if ([regextestmobile evaluateWithObject:mobileNum] == YES)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

-(void)ActionRepeats:(NSTimer *)timer
{

    countdownTiem60--;
    [self.btnVerification setTitle:[NSString stringWithFormat:@"%@秒",[NSNumber numberWithInteger:countdownTiem60]] forState:UIControlStateNormal];
    if (countdownTiem60==0) {
        [self.btnVerification setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];

        countdownTiem60 = 60;
        [timer invalidate];
    }
    
    
}

# pragma mark - network request 请求验证码

-(void)VerifyCodeRequest{
    [[LoadingView shareLoadingView] show];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setTimeoutInterval:10];
    //    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];


    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应



    NSString *   strUrl = [NSString stringWithFormat:@"%@%@", HostServerGetArea,CodeGetCodeAction];
    NSDictionary *dicJSON   = @{

                                @"phone":_textPhoneNum.text,

                                };

    //    NSError *error;
    //    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicJSON options:NSJSONWritingPrettyPrinted error:&error];
    //    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //
    //    NSDictionary *param = nil;
    //
    //    param   = @{
    //                @"data":jsonString,
    //                };

    [manager POST:strUrl parameters:dicJSON success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [[LoadingView shareLoadingView] dismissAnimated:YES];

        NSDictionary * dicRespon  = responseObject;
        [self VerifyRequestWith:dicRespon];



    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[LoadingView shareLoadingView] dismissAnimated:YES];
        [[NetWarningView sharedNetWarningView] show];  //警告网络异常
        NSLog(@"Error: %@", error);
        NSLog(@"请求出错了: - %@ %@",
              [error localizedDescription],
              [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
        
        
    }];
    

    
}

-(void)VerifyRequestWith:(NSDictionary *)dicRespon
{


    NSString * string  = [dicRespon objectForKey:@"success"];

    if (string.integerValue  == 1)

    {

        self.strCode = [[NSString alloc] initWithFormat:@"%@",[dicRespon objectForKey:@"code"]];

        UIAlertView *  alter = [[UIAlertView alloc] initWithTitle:@"提示" message:[dicRespon objectForKey:@"message"] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
        
    }
    
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    if (textField == _textPhoneNum) {
        [_textVerificationCode becomeFirstResponder];
    }
    
    [textField resignFirstResponder];
    return YES;
}
-(void)btnBack:(UIButton *)btnback
{
    
    
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)btnSureAction:(id)sender {
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];



    BOOL mobileNum = [self VerifyMobileNumber:self.textPhoneNum.text];
   if (mobileNum == NO)

    {

        UIAlertView * alter  = [[UIAlertView alloc] initWithTitle:@"您的手机号码有误" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alter show];
        return ;

    }
    else if (![_textPassWord.text isEqualToString:_textAlingPasss.text])

    {

        UIAlertView * alter  = [[UIAlertView alloc] initWithTitle:@"两次密码不一致" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alter show];
        return ;

    }
    else if (![self.strCode isEqualToString:self.textVerificationCode.text])

    {

        UIAlertView * alter  = [[UIAlertView alloc] initWithTitle:@"比输入的验证码不对，请重新输入" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alter show];
        return ;
    }


    [self getmodeifyPassworRequest];

}



#pragma mark - network request getmodeifyPassworRequest

-(void)getmodeifyPassworRequest
{
    [[LoadingView shareLoadingView] show];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,modify_passwordAction];
    ShareUserModel * shareUser  = [ShareUserModel shareUserModel];



    NSString * strPaw = [Common md5_32:_textPassWord.text];

    
    NSDictionary *params = @{

                             @"password":[NSString stringWithFormat:@"%@",strPaw],
                             @"phone":self.textPhoneNum.text,
                             @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId]

                             };




    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {


         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];

         NSDictionary * dicRespon = responseObject;
         [self ModifyMessageRequestSuccessWith:dicRespon];

         [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[LoadingView shareLoadingView] dismissAnimated:YES];
         [[NetWarningView sharedNetWarningView] show];  //警告网络异常
         //              NSData *doubi = operation.error    ;
         //                  //     JSON格式的NSString转换成NSMutableDictionary
         //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //              NSError *err = nil;
         //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         NSLog(@"Error: %@", error);
         NSLog(@"请求出错了: - %@ \n%@",
               [error localizedDescription],
               [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];

}


-(void)ModifyMessageRequestSuccessWith:(NSDictionary *)dicRespon
{

    NSString * code = [dicRespon objectForKey:@"success"];
    if (code.integerValue ==1)
    {




        LoginViewController * Loginview = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];

        [self presentViewController:Loginview animated:YES completion:^{

        }];

        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];


    }
    else
    {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];

    }

}

@end
